package com.itechart.watchfacts.controller;

import com.itechart.watchfacts.domain.WatchEntry;
import com.itechart.watchfacts.service.GeneralService;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Created by IntelliJ IDEA.
 * User: E.Krasnotschek
 * Date: 7/31/13
 * Time: 8:50 AM
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping(value = "/watchEntry")
public class WatchEntryController extends ControllerBase<WatchEntry>{

    public WatchEntryController(){
        listView =  "watchEntry";
        listUrl = "/watchEntry/list";
        modelAttrCreate = "watchEntry";
        modelAttrList = "watchEntryList";
    }

    @Autowired
    @Qualifier("watchEntryServiceImpl")
    public void setService(GeneralService<WatchEntry> service){
        this.service = service;
    }


    @Override
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(Model model){
        model.addAttribute(modelAttrCreate, new WatchEntry());
        model.addAttribute(modelAttrList, service.list());

        return listView;
    }

    @Override
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String create(Model model){
        return list(model);
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public String create(@ModelAttribute(value = "watchEntry") WatchEntry watchEntry){
        try{
            service.create(watchEntry);
        }catch (ConstraintViolationException e){
            //handle the situation when the new color duplicates existing one
        }
        return "redirect:"+ listUrl;
    }

    @Override
    @RequestMapping(value="/delete/{id}")
    public String delete(@PathVariable("id") int id){
        service.delete(id);

        return "redirect:" + listUrl;
    }
}
